import * as ImagePicker from "expo-image-picker";
import { TouchableOpacity, View, Text, Image, Platform } from "react-native";
import styles from "./index.style";
import AntDesign from "@expo/vector-icons/AntDesign";
import React from "react";
import { useTheme } from "@/contexts/ThemeContext";
import useUserProfileStateStore from "@/store/user-profile";
import { updateAvatarApi } from "@/services/api/user";
import { ResponseCode } from "@/types/api-common";
import { useUserProfileActions } from "@/hooks/user/user-profile";
export default function AvatarPicker() {
  const { currentUser } = useUserProfileStateStore().state;
  const { saveOrUpdateUserProfile } = useUserProfileActions();
  const { colors, themeMode } = useTheme();
  const createFormData = async (uri: string) => {
    const filename = uri.split("/").pop() || "avatar.jpg";
    const fileType = filename.split(".").pop();
    const formData = new FormData();
    formData.append("file", {
      uri: Platform.OS === "ios" ? uri.replace("file://", "") : uri,
      name: filename,
      type: `image/${fileType}`,
    } as any);

    return formData;
  };

  // 上传头像到服务器
  const uploadAvatar = async (formData: FormData) => {
    const result = await updateAvatarApi(formData);
    if (result.data.code === ResponseCode.SUCCESS) {
      await saveOrUpdateUserProfile({
        ...currentUser,
        avatar: result.data.data.url,
      });
    }
  };

  // 选择头像处理
  const pickAvatar = async () => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.8,
    });

    if (!result.canceled && result.assets?.[0]?.uri) {
      const formData = await createFormData(result.assets[0].uri);
      await uploadAvatar(formData);
    }
  };

  return (
    <TouchableOpacity
      style={[styles.avatarRow, { backgroundColor: colors.background }]}
      onPress={pickAvatar}
    >
      <View style={styles.avatarLeft}>
        <AntDesign name="picture" size={24} color={colors.text.primary} />
        <Text style={[styles.label, { color: colors.text.primary }]}>头像</Text>
      </View>
      <View style={styles.avatarRight}>
        <Image source={{ uri: currentUser.avatar }} style={styles.avatar} />
      </View>
    </TouchableOpacity>
  );
}
